import 'package:get/get.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/mixin/realtime_info_mixin.dart';
import 'package:inmotion_pro/service/realtime_data_server/realtime_data_polling_timer_helper.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';

import '../../../service/cache_config_service.dart';
import '../../../service/global_service.dart';
import '../../models/realtime_item.dart';
import '../constant/main_constant.dart';
import 'state.dart';

class VehicleRealtimeDetailController extends GetxController
    with CacheMixin, RealtimeInfoMixin {
  final VehicleRealtimeDetailState state = VehicleRealtimeDetailState();

  // 当前总里程
  double _totalMileage = 0.0;

  // 当前电池电量
  double _batteryPercent = 0.0;

  // 预估续航
  double _estimatedRemainingMileage = 0.0;

  @override
  void onInit() {
    super.onInit();
    if (GlobalService.to.cacheRealtimeItems.isEmpty) {
      // 如果缓存的实时信息列表为空，则使用默认的
      state.realtimeItems.value = MainConstant.totalRealtimeItemList;
    } else {
      // 使用缓存的实时信息列表
      state.realtimeItems.value = GlobalService.to.cacheRealtimeItems
          .map((item) => item.copyWith(isEditable: false))
          .toList();
    }

    // 延迟200毫秒，确保页面渲染完成后再监听变化
    Future.delayed(const Duration(milliseconds: 200), () {
      _listenRealtimeItemsChanges();
    });
  }

  // 监听实时信息列表变化
  _listenRealtimeItemsChanges() {
    Loading.showLoading(null);
    // 开始轮询实时数据
    realtimeInfoMixinStartLoopToGetVehicleRealTimeData(
      pollingTypes: RealtimeDataPollingTimeHelper.vehicleDetailPagePollingTypes,
      realtimeInfoCallback: (p0) {
        _batteryPercent = p0.batteryPercentage;
        _estimatedRemainingMileage = p0.estimatedRemainingMileage;
        var speedObj = CacheConfigService.to.metricUnit(p0.speed);
        state.currentSpeed.value = speedObj.$1;
        state.speedUnit.value = "${speedObj.$2}/h";
        state.currentVoltage.value = p0.voltage;
        state.currentBatteryTemperature.value = p0.boardTemperature.toDouble();
        state.currentMotorTemperature.value = p0.motorTemperature.toDouble();
        state.currentOutputRate.value = p0.outputVectorVoltagePercentage;
        // 设置当前输出矢量百分比的最大值
        if (p0.outputVectorVoltagePercentage >
            state.currentOutputRateMax.value) {
          state.currentOutputRateMax.value = p0.outputVectorVoltagePercentage;
        }
        state.currentIq.value = p0.iq;
        // 设置当前电机相电流的最大值
        if (p0.iq > state.currentIqMax.value) {
          state.currentIqMax.value = p0.iq;
        }
        // 实时信息回调，刷新页面
        _refreshRealtimeItems(
          currentSpd: p0.speed,
          limitSpd: p0.limitSpd,
          livePower: p0.motorOutputPower,
          mosTemp: p0.mosTemperature,
          boardTemp: p0.boardTemperature,
          motorTemp: p0.motorTemperature,
          current: p0.current,
          iq: p0.iq,
          voltage: p0.voltage,
          motorTorque: p0.torque,
          outputVectorVoltagePercentage: p0.outputVectorVoltagePercentage,
        );
      },
      statisticsOnceCallback: (p0) {
        _refreshRealtimeItems(
          tripTime: p0.singleRideTimeString,
          tripMileage: p0.singleMileage,
          avgSpd: p0.avgSpeed,
          maxSpd: p0.maxSpd,
          maxPower: p0.maxPower,
          avgPower: p0.avgPower,
        );
      },
      statisticsTotalCallback: (p0) {
        _totalMileage = p0.totalMileage;
        _refreshRealtimeItems(
          totalMileage: p0.totalMileage,
          upTime: p0.totalPowerOnTimeString,
          energyConsumption: p0.energyConsumption,
          energyRecovery: p0.energyRecovery,
        );
      },
    ).then((success) {
      if (success) {
        Loading.dismiss();
      } else {
        Loading.showError(local.failed);
      }
    }).catchErrorHandler();
  }

  // 刷新实时信息Item
  _refreshRealtimeItems({
    String? tripTime,
    String? upTime,
    double? currentSpd,
    double? avgSpd,
    double? maxSpd,
    double? limitSpd,
    double? tripMileage,
    double? totalMileage,
    double? livePower,
    double? maxPower,
    double? avgPower,
    int? mosTemp,
    int? boardTemp,
    int? motorTemp,
    double? current,
    double? iq,
    double? voltage,
    double? energyConsumption,
    double? energyRecovery,
    double? motorTorque,
    double? outputVectorVoltagePercentage,
  }) {
    // 实时统计总数据回调，刷新页面
    for (var item in state.realtimeItems) {
      if (item.title == local.current_speed && currentSpd != null) {
        var currentSpdObj = CacheConfigService.to.metricUnit(currentSpd);
        item.value = currentSpdObj.$1.toStringAsFixed(1);
      } else if (item.title == local.average_speed && avgSpd != null) {
        var avgSpdObj = CacheConfigService.to.metricUnit(avgSpd);
        item.value = avgSpdObj.$1.toStringAsFixed(1);
      } else if (item.title == local.max_speed && maxSpd != null) {
        var maxSpdObj = CacheConfigService.to.metricUnit(maxSpd);
        item.value = maxSpdObj.$1.toStringAsFixed(1);
      } else if (item.title == local.speed_limit && limitSpd != null) {
        var limitSpdObj = CacheConfigService.to.metricUnit(limitSpd);
        item.value = limitSpdObj.$1.toStringAsFixed(1);
      } else if (item.title == local.trip_mileage && tripMileage != null) {
        var tripMileageObj = CacheConfigService.to.metricUnit(tripMileage);
        item.value = tripMileageObj.$1.toStringAsFixed(1);
      } else if (item.title == local.trip_time && tripTime != null) {
        item.value = tripTime;
      } else if (item.title == local.total_mileage && totalMileage != null) {
        var totalMileageObj = CacheConfigService.to.metricUnit(totalMileage);
        item.value = totalMileageObj.$1.toStringAsFixed(1);
      } else if (item.title == local.up_time && upTime != null) {
        item.value = upTime;
      } else if (item.title == local.power && energyConsumption != null) {
        item.value = energyConsumption.toStringAsFixed(1);
      } else if (item.title == local.recovered_energy &&
          energyRecovery != null) {
        item.value = energyRecovery.toStringAsFixed(1);
      } else if (item.title == local.realtime_power && livePower != null) {
        item.value = livePower.toStringAsFixed(1);
      } else if (item.title == local.max_power && maxPower != null) {
        item.value = maxPower.toStringAsFixed(1);
      } else if (item.title == local.average_power && avgPower != null) {
        item.value = avgPower.toStringAsFixed(1);
      } else if (item.title == local.mos_temperature && mosTemp != null) {
        item.value = mosTemp.toString();
      } else if (item.title == local.board_temperature && boardTemp != null) {
        item.value = boardTemp.toString();
      } else if (item.title == local.motor_temperature && motorTemp != null) {
        item.value = motorTemp.toString();
      } else if (item.title == local.current_curr && current != null) {
        item.value = current.toStringAsFixed(1);
      } else if (item.title == local.current_iq && iq != null) {
        item.value = iq.toStringAsFixed(1);
      } else if (item.title == local.voltage && voltage != null) {
        item.value = voltage.toStringAsFixed(1);
      } else if (item.title == local.motor_torque && motorTorque != null) {
        item.value = motorTorque.toStringAsFixed(1);
      } else if (item.title == local.output_rate &&
          outputVectorVoltagePercentage != null) {
        item.value = outputVectorVoltagePercentage.toStringAsFixed(1);
      }
    }
    state.realtimeItems.refresh();
  }

  // 编辑/应用按钮点击事件
  editRealtimeItemsOnTap() {
    if (state.isEdit.value) {
      // 应用
      state.isEdit.value = false;
      Loading.showSuccess(local.apply_success);
      // 保存到缓存
      cacheMixinCacheMixinNewCacheVehicleRealtimeData(
        GlobalService.to.currentVehicleModel.value.bleName,
        state.realtimeItems.map((item) => item.toMap()).toList(),
        batteryPercent: _batteryPercent,
        estimatedRemainingMileage: _estimatedRemainingMileage,
        totalMileage: _totalMileage,
      );
    } else {
      // 编辑
      state.isEdit.value = true;
    }
  }

  // 实时信息Item选中事件
  realtimeItemSelectedOnTap(int index, bool isSelected) {
    // 找到原始数据中最大的priority
    int maxIndex = 0;
    for (var item in state.realtimeItems) {
      if (item.selectedIndex > maxIndex) {
        maxIndex = item.selectedIndex;
      }
    }
    // 如果选中，则分配一个新的priority（最大+1）
    if (isSelected) {
      state.realtimeItems[index].selectedIndex = maxIndex + 1;
    } else {
      state.realtimeItems[index].selectedIndex = 0;
    }
    state.realtimeItems[index].isSelected = isSelected;
    // 如何selectedIndex按照state.realtimeItems的数组顺序，出现了5，3，1，则变为3，2，1
    List<RealtimeItemModel> selectedItems =
        state.realtimeItems.where((item) => item.isSelected).toList();
    // 按照selectedIndex降序排列
    selectedItems.sort((a, b) => b.selectedIndex.compareTo(a.selectedIndex));
    // 重新分配selectedIndex
    for (int i = 0; i < selectedItems.length; i++) {
      selectedItems[i].selectedIndex = selectedItems.length - i;
    }
    // 将重新分配后的selectedIndex赋值回state.realtimeItems
    for (var item in state.realtimeItems) {
      for (var selectedItem in selectedItems) {
        if (item.title == selectedItem.title) {
          item.selectedIndex = selectedItem.selectedIndex;
        }
      }
    }
    state.realtimeItems.refresh();
  }

  // 筛选选中的，同时选中的按照selectedIndex升序排列
  List<RealtimeItemModel> sortedRealtimeItems(List<RealtimeItemModel> items) {
    List<RealtimeItemModel> selectedItems =
        items.where((item) => item.isSelected).toList();
    // 按照selectedIndex升序排列
    selectedItems.sort((a, b) => a.selectedIndex.compareTo(b.selectedIndex));
    return selectedItems;
  }
}
